package com.study.a03udpdemo2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReceiveMessageDemo {
    public static void main(String[] args) throws IOException {

        //要先启动接收端，才能接收数据
        //接收绑定端口，与发送端口一致
        DatagramSocket ds=new DatagramSocket(10000);

        //创建DatagramPacket对象（快递包裹）
        //接收数据用这个包裹接收

            DatagramPacket dp=new DatagramPacket(new byte[1024],1024);

            while (true) {
            //接收数据
            ds.receive(dp);

            //解析数据包
            byte[] data=dp.getData();
            int length=dp.getLength();
            InetAddress address=dp.getAddress();
            int port=dp.getPort();

            System.out.println("收到来自"+address+"的消息："+new String(data,0,length));
            if(new String(data,0,length).equals("exit")){
                break;
            }
        }

        ds.close();
    }
}
